package cn.xyt.server;

import static java.nio.ByteOrder.LITTLE_ENDIAN;

import java.nio.ByteOrder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.tom.kit.IoBuffer;
import cn.xyt.dto.Message;
import cn.xyt.util.NettyContextUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.EncoderException;
import io.netty.handler.codec.MessageToByteEncoder;

public class BaseOutEncoder extends MessageToByteEncoder<Message>{

	private Logger log = LoggerFactory.getLogger(BaseOutEncoder.class);
	
	@Override
	protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
		log.info("encode msg header={} body={}", msg.getHeader());
		IoBuffer buf = IoBuffer.allocate(200);
		buf.buf().order(LITTLE_ENDIAN);
		buf.writeBytes(msg.getHeader().toByteBuf());
		if(msg.getBody()!=null && msg.getBody().length>0){
			buf.writeBytes(msg.getBody());
		}
		buf.writeByte(msg.getCheck());
		buf.flip();
		
		int len  = buf.limit();
		out.order(ByteOrder.LITTLE_ENDIAN).writeShort(len);
		out.writeBytes(buf.readBytes(0, len));
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		String  id = (String)NettyContextUtil.getAttr(ctx, "id");
		log.error(id + "::BaseOutEncoder.exceptionCaught::", cause);
		if(cause instanceof EncoderException){
			ctx.close();
		}
	}
	

}
